package com.heer.gymnasium.module.order.views;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.heer.amap.utils.ToastUtil;
import com.heer.gymnasium.R;
import com.heer.gymnasium.api.ResponseData.ApiResponse;
import com.heer.gymnasium.api.callback.BaseCallback;
import com.heer.gymnasium.base.BaseRefreshActivity;
import com.heer.gymnasium.constant.Type;
import com.heer.gymnasium.module.evaluate.views.EvaStoreActivity;
import com.heer.gymnasium.module.evaluate.views.MemberListActivity;
import com.heer.gymnasium.module.login.views.LoginActivity;
import com.heer.gymnasium.module.main.views.MainActivity;
import com.heer.gymnasium.module.order.beans.MyOrderBean;
import com.heer.gymnasium.module.order.beans.OrderResponseListBean;
import com.heer.gymnasium.util.DialogUtils;
import com.heer.gymnasium.util.StringUtils;
import com.orangegangsters.github.swipyrefreshlayout.library.SwipyRefreshLayoutDirection;
import com.zhihuiyun.library.commonadapter.QuickInterface;
import com.zhihuiyun.library.commonadapter.QuickTypeAdapter;
import com.zhihuiyun.library.commonadapter.ViewHolder;
import com.zhihuiyun.library.dialog.CommonDialog;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by yan on 2018/1/18.
 * 我的订单列表界面
 */

public class MyOrderListNewActivity extends BaseRefreshActivity {
    private static final int LAYOUT = R.layout.layout_order_list;
    private static final int OBLIGATION_ID = R.id.layout_order_list_obligation_ll;
    private static final int PAID_ID = R.id.layout_order_list_paid_ll;
    private static final int ALL_ID = R.id.layout_order_list_all_ll;
    private static final int LISTVIEW_ID = R.id.layout_myorder_lv;
    private static final int REFRESH_ID = R.id.layout_myorder_srl;

    private static final int OBLIGATION_RB_ID = R.id.layout_order_list_obligation_rb;
    private static final int PAID_RB_ID = R.id.layout_order_list_paid_rb;
    private static final int ALL_RB_ID = R.id.layout_order_list_all_rb;

    //    item
    private static final int ITEM_LAYOUT = R.layout.item_order;
    private static final int ITEM_STORENAME = R.id.item_order_storename_tv;
    private static final int ITEM_ORDER_TYPE = R.id.item_order_type_iv;//拼或约
    private static final int ITEM_PAY_STATE = R.id.item_order_paystate_tv;
    private static final int ITEM_ORDER_LV = R.id.item_order_lv;
    private static final int ITEM_ON_OFF = R.id.item_order_openOrclose_iv;
    private static final int ITEM_MONEY = R.id.item_order_money_tv;
    private static final int ITEM_TOTAL = R.id.item_order_total_tv;
    private static final int ITEM_NUMBER = R.id.item_order_number_tv;
    private static final int ITEM_TIME = R.id.item_order_ordertime_tv;
    private static final int ITEM_BOTTON_RIGHT = R.id.item_order_bottom_evaOrCancle_tv;
    private static final int ITEM_BOTTON_EVA_STORE = R.id.item_order_bottom_evaluate_store_tv;
    //item下的详情item
    private static final int LIST_LAYOUT = R.layout.item_order_list;
    private static final int LIST_NAME = R.id.item_order_list_storename_tv;
    private static final int LIST_STORELIST = R.id.item_order_list_storelist_tv;
    private static final int LIST_TIME = R.id.item_order_list_time_tv;
    private static final int LIST_MONEY = R.id.item_order_list_money_tv;
    private static final int LIST_TOTAL = R.id.item_order_list_money_label_tv;
    private static final int LIST_ORDERSTATUS = R.id.item_order_list_status_tv;
    private static final int LIST_SINGLE_NUM = R.id.item_order_list_num_tv;
    private List<MyOrderBean> data;
    private QuickTypeAdapter<MyOrderBean> adapter;

    @BindView(OBLIGATION_RB_ID)
    RadioButton obligationRadioButton;
    @BindView(PAID_RB_ID)
    RadioButton paidRadioButton;
    @BindView(ALL_RB_ID)
    RadioButton allRaioButton;
    @BindView(LISTVIEW_ID)
    ListView listView;

    //1:未付款，2：已付款,不传/0全部
    private int type = 1;
    //    11:订场,21:购卡,31:充值,41：私教
    private static final int ORDER_TYPE_RESERVATION = 11, ORDER_TYPE_CARD = 21, ORDER_TYPE_RECHARGE = 31, ORDER_TYPE_COACH = 41;

    private Activity $this;

    /**
     * TODO 界面跳转，传参需定义
     *
     * @param context
     */
    public static void startActivity(Context context, int orderStatus) {
        Intent intent = new Intent(context, MyOrderListNewActivity.class);
        intent.putExtra(EXTRA_TYPE, orderStatus);
        context.startActivity(intent);
    }

    @Override
    protected void init() {
        super.init();
        $this = this;
        setContentView(LAYOUT);
        setRefreshResId(REFRESH_ID);
    }

    @Override
    protected void initView() {
        super.initView();
        titleUtils.setTitleText("我的订单");
        titleUtils.startMainActivity($this);
        data = new ArrayList<>();
        type = getIntent().getIntExtra(EXTRA_TYPE, 1);
        if (type == 1) {
            obligationRadioButton.setChecked(true);
            paidRadioButton.setChecked(false);
            allRaioButton.setChecked(false);
        } else if (type == 2) {
            obligationRadioButton.setChecked(false);
            paidRadioButton.setChecked(true);
            allRaioButton.setChecked(false);
        }
        adapter = new QuickTypeAdapter<MyOrderBean>(this, data, ITEM_LAYOUT) {

            @Override
            public void bindData4View(final ViewHolder holder, final MyOrderBean data, final int type, final int pos) {
                holder.setText(ITEM_STORENAME, data.getStadiumName());
                holder.setText(ITEM_MONEY, data.getPayMoney());
                holder.setText(ITEM_NUMBER, "共" + data.getOrderNum() + "件");
                holder.setText(ITEM_TIME, "下单时间：" + data.getOrderTime());
                topStatus(holder, data);
                bottomRightStatus(holder, data);
                fillData(holder, data, pos);

            }
        };
        listView.setAdapter(adapter);
    }

    //顶部右侧的显示状态
    private void topStatus(ViewHolder holder, final MyOrderBean data) {
        if (data.getOrderStatus().equals("1") || data.getOrderStatus().equals("5") || data.getOrderStatus().equals("6")) {
            if (data.getPayStaus().equals("0")) {
                holder.setText(ITEM_PAY_STATE, "待付款");
            } else {
                holder.setText(ITEM_PAY_STATE, "已支付");
            }
        } else if (data.getOrderStatus().equals("2") || data.getOrderStatus().equals("4")) {
            holder.setText(ITEM_PAY_STATE, "已取消");
        } else if (data.getOrderStatus().equals("3")) {
            holder.setText(ITEM_PAY_STATE, "已关闭");
        } else if (data.getOrderStatus().equals("8")) {
            holder.setText(ITEM_PAY_STATE, "已退款");
        } else if (data.getOrderStatus().equals("0")) {
            holder.setText(ITEM_PAY_STATE, "订单无效");
        } else {
            holder.setVisibility(ITEM_PAY_STATE, View.GONE);
        }
    }

    // item数据填充
    private void fillData(final ViewHolder holder, final MyOrderBean bean, final int pos) {
        if (bean.getOrderType().equals(Type.STADIUM_TYPE) || bean.getOrderType().equals(Type.STADIUM_TICKET_TYPE)
                || bean.getOrderType().equals(Type.STADIUM_YUE) || bean.getOrderType().equals(Type.STADIUM_FELLOW)) {
            if (bean.getOrderType().equals(Type.STADIUM_YUE)) {
                holder.setVisibility(ITEM_ORDER_TYPE, View.VISIBLE);
                holder.setBg(ITEM_ORDER_TYPE, R.drawable.ic_yue);
            } else if (bean.getOrderType().equals(Type.STADIUM_FELLOW)) {
                holder.setVisibility(ITEM_ORDER_TYPE, View.VISIBLE);
                holder.setBg(ITEM_ORDER_TYPE, R.drawable.ic_pin);
            } else {
                holder.setVisibility(ITEM_ORDER_TYPE, View.GONE);
            }
            List<MyOrderBean.DetialStadium> list = new ArrayList<>();
            if (bean.getDetailList() != null && bean.getDetailList().size() > 0) {
                holder.setVisibility(ITEM_ON_OFF, View.VISIBLE);
                if (!bean.isOpen()) {
                    holder.setBg(ITEM_ON_OFF, R.drawable.ic_tow_down);
                    list.add((MyOrderBean.DetialStadium) bean.getDetailList().get(0));
                } else {
                    holder.setBg(ITEM_ON_OFF, R.drawable.ic_tow_up);
                    list.addAll(bean.getDetailList());
                }
                if (bean.getDetailList().size() == 1) {
                    holder.setVisibility(ITEM_ON_OFF, View.GONE);
                }
            } else {
                holder.setVisibility(ITEM_ON_OFF, View.GONE);
            }

            ((ListView) holder.getView(ITEM_ORDER_LV)).setAdapter(new QuickTypeAdapter<MyOrderBean.DetialStadium>($this, list, LIST_LAYOUT) {
                @Override
                public void bindData4View(ViewHolder holder, final MyOrderBean.DetialStadium data, int type, int pos) {
                    holder.setText(LIST_NAME, bean.getStadiumName());
                    holder.setText(LIST_STORELIST, data.getPlaceName());
                    holder.setText(LIST_TIME, data.getTime());
                    holder.setVisibility(LIST_TIME, View.VISIBLE);
                    holder.setText(LIST_MONEY, data.getPrice());
                    if (data.getCancelStatus().equals("1") && data.getOrderStatus().equals("1") && bean.getPayStaus().equals("1")) {
                        holder.setText(LIST_ORDERSTATUS, "取消单场");
                        holder.setVisibility(LIST_ORDERSTATUS, View.VISIBLE);
                    } else if (data.getIsEval().equals("0") && data.getOrderStatus().equals("2")) {
                        holder.setText(LIST_ORDERSTATUS, "评价");
                        holder.setVisibility(LIST_ORDERSTATUS, View.VISIBLE);
                    } else if (data.getOrderStatus().equals("4")) {
                        holder.setText(LIST_ORDERSTATUS, "已取消");
                        holder.setVisibility(LIST_ORDERSTATUS, View.VISIBLE);
                    } else {
                        holder.setVisibility(LIST_ORDERSTATUS, View.GONE);
                    }
                    holder.setVisibility(LIST_SINGLE_NUM, View.GONE);
                    holder.setLis(LIST_ORDERSTATUS, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if (((TextView) view).getText().equals("评价")) {
                                startEvaStore(data.getDetailId(), "1");
                            } else if (((TextView) view).getText().equals("取消单场")) {
                                DialogUtils.showDialog($this, "提示", "确定删除该订单？", "", "", new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        if (view.getId() == CommonDialog.RES_ID_POSITIVE) {
                                            cancelOrder("2", "", data.getDetailId());
                                        }
                                        DialogUtils.dismissDialog();
                                    }
                                });
                            }
                        }
                    });

                }
            });
            holder.setLis(ITEM_ON_OFF, new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (bean.isOpen()) {
                        data.get(pos).setOpen(false);
                        holder.setBg(ITEM_ON_OFF, R.drawable.ic_tow_down);
                    } else {
                        data.get(pos).setOpen(true);
                        holder.setBg(ITEM_ON_OFF, R.drawable.ic_tow_up);
                    }
                    adapter.notifyDataSetChanged();
                }
            });
        } else if (bean.getOrderType().equals(Type.BUY_CARD_TYPE)) {//
            holder.setVisibility(ITEM_ON_OFF, View.GONE);
            ((ListView) holder.getView(ITEM_ORDER_LV)).setAdapter(new QuickTypeAdapter<MyOrderBean.DetailCard>($this, bean.getDetailList(), LIST_LAYOUT) {
                @Override
                public void bindData4View(ViewHolder holder, MyOrderBean.DetailCard data, int type, int pos) {
                    holder.setText(LIST_NAME, bean.getStadiumName());
                    holder.setText(LIST_STORELIST, data.getCardType());
                    holder.setText(LIST_MONEY, data.getPrice());
                    holder.setVisibility(LIST_TIME, View.GONE);
                    holder.setVisibility(LIST_ORDERSTATUS, View.GONE);
                }
            });
        } else if (bean.getOrderType().equals(Type.RECHARGE_TYPE)) {
            holder.setVisibility(ITEM_ON_OFF, View.GONE);
            ((ListView) holder.getView(ITEM_ORDER_LV)).setAdapter(new QuickTypeAdapter<MyOrderBean.DetailRecharge>($this, bean.getDetailList(), LIST_LAYOUT) {
                @Override
                public void bindData4View(ViewHolder holder, MyOrderBean.DetailRecharge data, int type, int pos) {
                    holder.setText(LIST_NAME, "充值卡");
                    holder.setText(LIST_STORELIST, "¥" + data.getPrice() + "赠¥" + data.getGiveMoney());
                    holder.setText(LIST_MONEY, data.getPrice());
                    holder.setVisibility(LIST_TIME, View.GONE);
                    holder.setVisibility(LIST_ORDERSTATUS, View.GONE);
                }
            });
        } else if (bean.getOrderType().equals(Type.COACH_TYPE)) {
            holder.setVisibility(ITEM_ON_OFF, View.GONE);
            ((ListView) holder.getView(ITEM_ORDER_LV)).setAdapter(new QuickTypeAdapter<MyOrderBean.DetailCoach>($this, bean.getDetailList(), LIST_LAYOUT) {
                @Override
                public void bindData4View(ViewHolder holder, MyOrderBean.DetailCoach data, int type, int pos) {
                    holder.setText(LIST_NAME, "私教卡");
                    holder.setText(LIST_STORELIST, data.getCoachName());
                    holder.setText(LIST_MONEY, data.getPrice());
                    holder.setVisibility(LIST_TIME, View.GONE);
                    holder.setVisibility(LIST_ORDERSTATUS, View.GONE);
                    if (bean.getOrderType().equals(Type.COACH_TYPE)) {
                        holder.setVisibility(LIST_SINGLE_NUM, View.VISIBLE);
                        holder.setText(LIST_SINGLE_NUM, "x" + bean.getOrderNum());
                    } else {
                        holder.setVisibility(LIST_SINGLE_NUM, View.GONE);
                    }
                }
            });
        }
    }

    //底部右侧的显示状态
    private void bottomRightStatus(ViewHolder holder, final MyOrderBean bean) {
        holder.setVisibility(ITEM_BOTTON_RIGHT, View.GONE);
        holder.setVisibility(ITEM_BOTTON_EVA_STORE, View.GONE);

        if (bean.getPayStaus().equals("0") && ((bean.getOrderStatus().equals("1")) || (bean.getOrderStatus().equals("5")) || (bean.getOrderStatus().equals("6")))) {
            holder.setText(ITEM_BOTTON_RIGHT, "付款");
            holder.setVisibility(ITEM_BOTTON_RIGHT, View.VISIBLE);
        } else {
            if (bean.getOrderType().equals(Type.STADIUM_FELLOW) || bean.getOrderType().equals(Type.STADIUM_YUE)) {
                if (!bean.isEvalStore() && bean.getOrderStatus().equals("1")) {
                    holder.setVisibility(ITEM_BOTTON_EVA_STORE, View.VISIBLE);
                }
                if (bean.getCancelStatus().equals("1") &&
                        ((bean.getOrderStatus().equals("1")) || (bean.getOrderStatus().equals("5")) || (bean.getOrderStatus().equals("6")))) {
                    holder.setVisibility(ITEM_BOTTON_RIGHT, View.VISIBLE);
                    holder.setText(ITEM_BOTTON_RIGHT, "取消订单");

                } else if (bean.getIsEval().equals("0") && bean.getOrderStatus().equals("1")) {
                    holder.setVisibility(ITEM_BOTTON_RIGHT, View.VISIBLE);
                    if (bean.getOrderType().equals(Type.STADIUM_FELLOW)) {
                        holder.setText(ITEM_BOTTON_RIGHT, "评价成员");
                    } else {
                        holder.setText(ITEM_BOTTON_RIGHT, "评价战队");
                    }
                }
            } else {
                MyOrderBean.CommonDetial detialItem = (MyOrderBean.CommonDetial) bean.getDetailList().get(0);

                if (detialItem.getCancelStatus().equals("1")) {
                    holder.setText(ITEM_BOTTON_RIGHT, "取消订单");
                    holder.setVisibility(ITEM_BOTTON_RIGHT, View.VISIBLE);
                } else {
                    if (!bean.getOrderType().equals(Type.STADIUM_TYPE)) {
                        if (detialItem.getIsEval().equals("0") && detialItem.getOrderStatus().equals("2")) {
                            holder.setText(ITEM_BOTTON_RIGHT, "评价");
                            holder.setVisibility(ITEM_BOTTON_RIGHT, View.VISIBLE);
                        }
                    }
                }

            }
        }
        holder.setLis(ITEM_BOTTON_RIGHT, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (((TextView) view).getText().equals("评价")) {
                    String evatype;
                    if (bean.getOrderType().equals(Type.COACH_TYPE)) {
                        evatype = "0";
                    } else {
                        evatype = "1";
                    }
                    startEvaStore(((MyOrderBean.CommonDetial) bean.getDetailList().get(0)).getDetailId(), evatype);
                } else if (((TextView) view).getText().equals("付款")) {
                    if (bean.getOrderStatus().equals("1") || bean.getOrderStatus().equals("2")) {
                        OrderActivity.startActivity($this, OrderActivity.OrderType.from_order, bean.getOrderId(), bean.getOrderType(), true);
                    } else
                        OrderActivity.startActivity($this, OrderActivity.OrderType.from_order, bean.getOrderId(), bean.getOrderType());
                } else if (((TextView) view).getText().equals("取消订单")) {
                    DialogUtils.showDialog($this, "提示", "确定删除该订单？", "", "", new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if (view.getId() == CommonDialog.RES_ID_POSITIVE) {
                                cancelOrder("1", bean.getOrderId(), null);
                            }
                            DialogUtils.dismissDialog();
                        }
                    });
                } else if (((TextView) view).getText().equals("评价成员")) {
                    MemberListActivity.startActivity($this, bean.getOrderId());
                } else if (((TextView) view).getText().equals("评价战队")) {
                    startEvaStore(bean.getOrderId(), "3");
                }
            }
        });
        holder.setLis(ITEM_BOTTON_EVA_STORE, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startEvaStore(bean.getOrderId(), "5");
            }
        });
    }


    @Override
    protected void loadData(boolean loadMore) {
        super.loadData(loadMore);
        getOrderList();
        if (layoutRefresh.isRefreshing()) {
            layoutRefresh.setRefreshing(false);
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        loadData(false);
    }

    @OnClick({OBLIGATION_ID, PAID_ID, ALL_ID})
    public void onClick(View view) {
        switch (view.getId()) {
            case OBLIGATION_ID:
                obligationRadioButton.setChecked(true);
                paidRadioButton.setChecked(false);
                allRaioButton.setChecked(false);
                type = 1;
                pageNo = 1;
                getOrderList();
                break;
            case PAID_ID:
                obligationRadioButton.setChecked(false);
                paidRadioButton.setChecked(true);
                allRaioButton.setChecked(false);
                type = 2;
                pageNo = 1;
                getOrderList();
                break;
            case ALL_ID:
                obligationRadioButton.setChecked(false);
                paidRadioButton.setChecked(false);
                allRaioButton.setChecked(true);
                type = 0;
                pageNo = 1;
                getOrderList();
                break;
        }
    }

    //    获得订单数据
    private void getOrderList() {
        mAppHelper.apiService().getOrderList(type + "", pageNo + "").enqueue(new BaseCallback<ApiResponse<OrderResponseListBean>>() {

            @Override
            public void onSuccess(Call<ApiResponse<OrderResponseListBean>> call, Response<ApiResponse<OrderResponseListBean>> response) {
                int total = StringUtils.toInt(response.body().getData().getTotal());
                int current = StringUtils.toInt(response.body().getData().getCurrent_page());
                int per_page = StringUtils.toInt(response.body().getData().getPer_page());
                if (total <= current * per_page) {
                    layoutRefresh.setDirection(SwipyRefreshLayoutDirection.TOP);
                } else {
                    layoutRefresh.setDirection(SwipyRefreshLayoutDirection.BOTH);
                }
                if (pageNo == 1) {
                    data.clear();
                }
                data.addAll(MyOrderBean.dataChange(response.body().getData().getData()));
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Call<ApiResponse<OrderResponseListBean>> call, Throwable t) {
                super.onError(call, t);
                if (pageNo == 1) {
                    data.clear();
                }
                adapter.notifyDataSetChanged();
            }
        });


    }

    //取消订单 类型1：取消整个订单，2：取消订单中的某一个
    private void cancelOrder(String type, String orderId, String detailId) {
        mAppHelper.apiService().cancelOrder(type, orderId, detailId).enqueue(new BaseCallback<ApiResponse<String>>() {
            @Override
            public void onSuccess(Call<ApiResponse<String>> call, Response<ApiResponse<String>> response) {
                getOrderList();
                ToastUtil.show($this, "取消订单成功");
            }
        });
    }

    /**
     * @param detailId
     * @param evatype  0:教练，1：场馆,2:用户,3:战队,4:评价用户,5评价店铺
     */
    private void startEvaStore(String detailId, String evatype) {
        EvaStoreActivity.startActivity($this, detailId, evatype, type);
    }
}
